package org.chench.extra;

import org.zeromq.SocketType;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;

import java.io.IOException;
import java.util.Random;

/**
 * 将任务Push到分发到多个Worker
 * @author chench9@lenovo.com
 * @desc org.chench.extra.TaskVentilator
 * @date 3/20/19 7:04 PM
 */
public class TaskVentilator {

    public static void main(String[] args) {
        try {
            startVentilator();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void startVentilator() throws IOException, InterruptedException {
        try(ZContext context = new ZContext()) {
            ZMQ.Socket sender = context.createSocket(SocketType.PUSH);
            sender.bind("tcp://*:5557");

            System.out.println("Press Enter when the workers are ready: ");
            System.in.read();
            System.out.println("Sending tasks to workers\n");

            // 分发100个任务出去
            int totalMseconds = 0;
            Random random = new Random(System.currentTimeMillis());
            for(int i = 0; i < 100; i++) {
                int workload;
                //  Random workload from 1 to 100msecs
                workload = random.nextInt(100) + 1;
                totalMseconds += workload;
                System.out.print(workload + ".");
                String string = String.format("%d", workload);
                sender.send(string, 0);
            }
            System.out.println("\nTotal expected cost: " + totalMseconds + " msec");
            Thread.sleep(1000); //  Give 0MQ time to deliver
        }
    }
}
